package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 解决单线程远程调用丢失请求头
 */
@Configuration
public class MyFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            /**
             * feign远程之前，先被拦截,处理远程调用丢失请求头
             * @param requestTemplate
             */
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if(attributes==null){
                    return;
                }
                HttpServletRequest request = attributes.getRequest();
                //老请求请求头数据同步到新请求，Cookie
                requestTemplate.header("Cookie",request.getHeader("Cookie"));
            }
        };
    }
}
